import { Iframe, LeftOutlined, Toast, Button, class_esy, UpOutlined } from 'esy-ui';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { postGameOut } from '@/services';
import { useGlobalStore } from '@/mobx';
import { useNavigation } from '@/hooks';
import { lsGetItem, lsSetItem } from '@/utils';

function Game() {
  const params = useParams();
  const { changeState } = useGlobalStore();
  const navigation = useNavigation();
  const id = params?.id;
  const [show, setShow] = useState(false);
  const url = lsGetItem('game_ing_id');

  useEffect(() => {
    changeState('isLoading', true);
    return () => {
      postGameOut({ GameID: id });
      lsSetItem('game_ing_id', '');
      changeState('isLoading', false);
    };
  }, [changeState, id]);

  const onLoad = () => {
    console.info('加载成功');
    changeState('isLoading', false);
  };

  const onError = () => {
    if (url) {
      console.info('加载失败');
      changeState('isLoading', false);
      Toast.show({ content: 'failed' });
    }
  };

  const goBack = () => {
    navigation(-1);
  };

  const goDeposit = () => {
    navigation('/deposit');
  };

  const changeOpen = () => {
    setShow((isS) => !isS);
  };

  return (
    <div className='relative h-full bg-body'>
      <div className={class_esy(['absolute top-0 left-0 right-0 bg-head transition-transform duration-150', show ? '' : '-translate-y-full'])}>
        <div className='flex items-center justify-between py-2 px-1 text-white'>
          <LeftOutlined className='text-xs p-2' onClick={goBack} />
          {/* <div className='text-sm font-bold ml-6 max-w-36 truncate text-center'>{title}</div> */}
          <Button className='rounded-full text-white font-bold bg-color-16 absolute right-3' size='small' onClick={goDeposit}>
            Deposit
          </Button>
          <div className='absolute z-10 -bottom-4 left-40 mx-auto w-16 h-4 bg-mask flex items-center justify-center rounded-b' onClick={changeOpen}>
            <UpOutlined className={class_esy(['text-xs transition-transform duration-150 scale-85', show ? '' : 'rotate-180'])} />
          </div>
        </div>
      </div>
      <Iframe id='game-page' className='h-full w-full' src={url} onLoad={onLoad} onError={onError} />
    </div>
  );
}
export default observer(Game);
